import React, { Component } from 'react';
import { ListView, List } from 'antd-mobile';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import '../css/nas.css';
import ICON_CLOSE from '../images/close.png';
import {getTrackList, getUuid, getAudiosByAlbum, convetAudiosByAlbum} from '../utils';
import { COMMON_CATEGORY_ID, BAIDU_CATEGORY_ID } from '../config';

/**
 * 新的播放列表
 */
const Item = List.Item;
class NewPlayList extends Component {
    constructor(props, context) {
        super(props, context);
        const ds = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });

        let audio_id = this.props.audio ? this.props.audio.audio_id: 0 ;
        let isPalying = this.props.isPlaying;
        let album = this.props.album;
        let count = 0;
        let audioList = [];
        if (album && album.list) {
            audioList = album.list;
            count = album.count || audioList.length;
        }

        // 专辑数小于20
        let hasMore = true;
        if (count !== 0 && count < 20) {
            hasMore = false;
        }

        this.state = {
            album: album,
            audioList: audioList,
            audio_id: audio_id,
            isPalying: isPalying,
            dataSource: ds.cloneWithRows(audioList),
            height: document.documentElement.clientHeight * 3,
            isLoading: true,
            hasMore: hasMore,
            count: count
        }
    }

    componentDidMount() {
        this._isMounted = true;
        let hei = document.documentElement.clientHeight - ReactDOM.findDOMNode(this.lv).parentNode.offsetTop;
        this.setState({
            height: hei,
        });
    }

    handleItemClick(audio) {
        this.props.playAudioList(audio)
    }

    hiddenPlaylist(){
        this.props.hidden();
    }

    onEndReached = (event) => {
        if (this.state.isLoading && !this.state.hasMore) {
            return;
        }
        if(this.props.category_id === COMMON_CATEGORY_ID || this.props.category_id === BAIDU_CATEGORY_ID){
            this.setState({ isLoading: true });
            this.loadMore();
        }
    }

    /**
     * 分页获取数据, 如果没有包含upid,表示正常的获取音频信息
     */
    loadMore(){
        const lastAudio = this.state.audioList[this.state.audioList.length-1];
        const albumId =this.state.album.album_id;
        console.log(`episode:${lastAudio.episode},id;${lastAudio.id}`);
        if (lastAudio.episode) {
            getTrackList(getUuid(), albumId, 20, lastAudio.episode, (result) => {
                if (!this._isMounted) {
                    return;
                }
                console.log(result.data);
                if (result.errcode === 0) {
                    if (result.data) {
                        const rowAudioList = convetAudiosByAlbum(result.data)
                        if (rowAudioList.length) {
                            const newAudioList = this.state.audioList.concat(rowAudioList)
                            this.setState({
                                audioList: newAudioList,
                                dataSource: this.state.dataSource.cloneWithRows(newAudioList),
                                isLoading: false,
                                hasMore: rowAudioList.length >= 20,
                                count:rowAudioList[0].track_num
                            });
                            this.props.updateAlbumAudioList(newAudioList);
                        } else {
                            this.setState({ isLoading: false, hasMore: false });
                        }
                    }else {
                        this.setState({ isLoading: false, hasMore: false });
                    }
                } else {
                    this.setState({ isLoading: false, });
                }
            })
        } else {
            getAudiosByAlbum(albumId, lastAudio.id, this.state.count, (data) => {
                if (!this._mounted) {
                    return;
                }
                console.log(data.data.length);
                if (data.errcode === 0) {
                    const len = data.data.length;
                    if (len > 0) {
                        const newAudioList = this.state.audioList.concat(data.data);
                        let albumCount = this.state.count;
                        if (albumCount === 0) {
                            albumCount = data.data[0].count;
                        }
                        this.setState({
                            audioList: newAudioList,
                            dataSource: this.state.dataSource.cloneWithRows(newAudioList),
                            isLoading: false,
                            hasMore: len >= 20,
                            count:albumCount
                        });
                        this.props.updateAlbumAudioList(newAudioList);
                    } else {
                        this.setState({ isLoading: false, hasMore: false });
                    }
                } else {
                    this.setState({ isLoading: false});
                }
            });
        }
    }

    makeDots() {
        const playState = this.state.isPalying ? 'header-music-icon-playing' : 'header-music-icon-paused';
        return (
            <div className="header">
                <div className="header-music-icon">
                    <div className="header-music-icon-animate ">
                        {
                            ['one', 'two', 'three', 'four'].map((ele, i) => {
                                return (
                                    <span key={i}
                                        className={classNames('header-music-icon-animate-' + ele, playState)}>
                                    </span>
                                )
                            })
                        }
                    </div>
                </div>
            </div>
        )
    }

    render() {
        const row = (audio, sectionID, rowID) => {
            return (
                <Item key={rowID} onClick={this.handleItemClick.bind(this, audio)} style={{ height: "42px"}}>
                    <div style={styles.item}>
                        {this.state.audio_id === audio.audio_id && this.makeDots()}
                        <p style={this.state.audio_id === audio.audio_id ? styles.current_name : styles.name}>{parseInt(rowID, 10) + 1}.{audio.name}</p>
                    </div>
                </Item>
            );
        };
        return (
            <div style={{ height: '100%', width: '100%', position: 'absolute' }}>
                <div style={{
                    height: '42px',
                    width: '100%',
                    position: 'absolute',
                    zIndex: 2,
                    display: 'flex',
                    background: "#eeeeee"
                }}>
                    <div style={{width:"20%",height:"42px"}}/>
                    <div style={styles.count}>
                        <span>播放列表({this.state.count})</span>
                    </div>
                    <div style={{width:"20%",height:"42px",display:'flex',justifyContent:"center",alignItems:"center"}} onClick={this.hiddenPlaylist.bind(this)}>
                     <img src={ICON_CLOSE} style={{ height: '20px', marginLeft: '16px' }} alt='' />
                    </div>
                </div>
                <div style={styles.play_content} id='popup_div'>
                    <ListView
                        ref={el => this.lv = el}
                        dataSource={this.state.dataSource}
                        renderFooter={() => (
                            <div style={{
                                padding: "12px",
                                textAlign: 'center',
                                fontSize: '13px',
                            }}>
                                {this.state.hasMore === true ? "正在加载内容..." : '没有更多音频了'}
                            </div>)}
                        renderRow={row}
                        style={{
                            height: this.state.height,
                            overflow: 'auto',
                            marginBottom:"8px",
                        }}
                        initialListSize={1000}
                        pageSize={20}
                        className="am-list"
                        scrollEventThrottle={100}
                        scrollRenderAheadDistance={300}
                        onEndReached={this.onEndReached}
                        onEndReachedThreshold={20}
                    />
                </div>
            </div>
        );
    }
}

export default NewPlayList;
const itemWidth = document.documentElement.clientWidth - 80;
const styles = {
    item: { width: '100%', height: "42px", display: 'flex', alignItems: "center" },
    name: {
        color: '#616161',
        fontSize: '13px',
        marginLeft: 5,
        width: itemWidth,
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        whiteSpace: 'nowrap'
    },
    current_name: {
        color: '#15a67c',
        fontSize: '14px',
        marginLeft: '5px',
        width: itemWidth,
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        whiteSpace: 'nowrap'
    },
    count: {
        height: '42px',
        width:"60%",
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: '#15a67c',
        fontSize: '15px',
    },
    play_content: {
        height: '95%',
        width: '100%',
        position: 'absolute',
        zIndex: 0,
        marginTop: "42px",
        overflow: 'scroll',
        marginBottom: "16px"
    },
}